<template>
  <div class="dv-charts-container" ref="refContainer">
    <div class="charts-canvas-container" ref="chartRef" />
  </div>
</template>

<script lang="ts">
import { uuid } from '../../utils';
import autoResize from '../../autoResize';
import { ref, defineComponent, watch, Ref, markRaw } from 'vue';
import * as echarts from 'echarts';
export default defineComponent({
	name: 'DvCharts',
	props: {
		option: {
			type: Object,
			default: () => ({}),
		},
	},
	setup(props) {
		const id = uuid();
		let refContainer: Ref<HTMLElement | null> = ref(null);
		let chartRef: Ref<HTMLElement | null> = ref(null);
		let chart: any = null;

		const afterAutoResizeMixinInit = () => {
			initChart();
		};
		const initChart = () => {
			chart = markRaw(echarts.init(chartRef.value!!));
			if (!props.option) return;
			chart.setOption(props.option);
		};
		const onResize = () => {
			if (!chart) return;
			chart.resize();
		};
		autoResize(refContainer, onResize, afterAutoResizeMixinInit, () => {});
		watch(
			() => props.option,
			() => {
				if (!chart) return;
				chart.setOption(props.option || {}, true);
			},
			{
				deep: true,
			},
		);
		return { id, refContainer, chartRef };
	},
});
</script>
